package job

import (
	"encoding/json"
	"git.supremind.info/product/box/vehicle/common"
	"git.supremind.info/product/box/vehicle/global"
	"git.supremind.info/product/box/vehicle/internal/dao"
	"git.supremind.info/product/box/vehicle/internal/dto"
	"git.supremind.info/product/box/vehicle/internal/util"
	"git.supremind.info/product/box/vehicle/internal/wsserver"
	"strings"
	"time"
)

func GetVmrModelData() {
	go func() {
		for {
			header := make(map[string]string)
			header[global.VmrSetting.AccessKey] = global.VmrSetting.AccessToken
			url := global.VmrSetting.Host + "/v1/msg/group/sidecar_01/event-detect-box"
			data, err := util.GetVmrData(url, header, 5*time.Second)
			if err != nil {
				common.Logger.Debugf("%v", err)
				time.Sleep(5 * time.Second)
				continue
			}
			common.Logger.Debugf("%v", data)
			if data == nil {
				time.Sleep(5 * time.Second)
				continue
			}

			vmrInterfaceResponse := dto.VmrInterfaceResponse{}
			jsonErr1 := util.ConvByJson(data, &vmrInterfaceResponse)
			if jsonErr1 != nil {
				time.Sleep(5 * time.Second)
				continue
			}

			if vmrInterfaceResponse.Code != 0 {
				common.Logger.Debugf("get model data error :%v", vmrInterfaceResponse)
				time.Sleep(5 * time.Second)
				continue
			}

			// 车型识别数据
			modelData := vmrInterfaceResponse.Data
			if modelData == nil {
				time.Sleep(5 * time.Second)
				continue
			}

			//vehicleModeData := make(map[string]interface{})
			vehicleModeData := modelData.(map[string]interface{})
			//jsonErr2 := util.ConvByJson(modelData, vehicleModeData)
			//if jsonErr2 != nil {
			//	time.Sleep(5 * time.Second)
			//	continue
			//}

			common.Logger.Debugf("get model data %v", vehicleModeData)

			err = handleVehicleModeData(&vehicleModeData)
			if err != nil {
				common.Logger.Error(err)
			}
		}
	}()
}

func handleVehicleModeData(data *map[string]interface{}) error {

	// 获取盒子信息
	url3 := global.VmrSetting.Host + "/v1/box"
	boxInfo, err3 := util.GetData(url3)
	if err3 != nil {
		return err3
	}
	vmrInterfaceResponse := dto.VmrInterfaceResponse{}
	util.ConvByJson(boxInfo, &vmrInterfaceResponse)

	info := dto.BoxInfo{}
	util.ConvByJson(vmrInterfaceResponse.Data, &info)

	extra := info.Extra

	body := make(map[string]interface{})
	vmrDataBody := (*data)["body"]
	util.ConvByJson(vmrDataBody, &body)

	body["gantry"] = extra["portal_id"]
	body["lane"] = extra["lane_number"]
	body["vmr_id"] = (*data)["id"]

	//headTime := (*data)["head_time"].(time.Time)
	headTime := body["head_time"].(string)
	var eventTime dao.BaseTime
	if headTime != "" {
		parse, timeErr := time.Parse("2006-01-02T15:04:05+08:00", headTime)
		if timeErr != nil {
			return timeErr
		}
		body["head_time"] = parse.Format("2006-01-02 15:04:05")
		eventTime.Scan(parse)
	}
	body["vmr_time"] = (*data)["time"]

	marshal, err := json.Marshal(body)
	if err != nil {
		return err
	}
	wsserver.SendModelMessage("model", marshal)

	hazardousChemicals := make([]string, 0)
	if body["hazardous_chemicals"] != nil {
		util.ConvByJson(body["hazardous_chemicals"], &hazardousChemicals)
	}

	vehicleModelData := dao.VehicleModelData{
		AxlesNumber:        body["axles_number"].(float64),
		BoxName:            info.BoxName,
		Gantry:             body["gantry"].(string),
		Lane:               body["lane"].(string),
		CompanyId:          1000,
		OrganizationId:     1000,
		EventId:            body["event_id"].(string),
		VehicleType:        body["vehicle_type"].(string),
		WheelsNumber:       body["wheels_number"].(float64),
		HazardousChemicals: strings.Join(hazardousChemicals, ","),
		Data:               string(marshal),
		PushStatus:         0,
		Source:             info.Hardware.SerialNumber,
		SerialNumber:       info.Hardware.SerialNumber,
		EventTime:          eventTime,
	}
	vehicleModelData.CreateTime.Scan(time.Now())
	vehicleModelData.UpdateTime.Scan(time.Now())
	modelDataId := dao.SaveVehicleModelData(&vehicleModelData)

	for _, s := range hazardousChemicals {
		vehicleModelChemical := dao.VehicleModelChemical{}
		vehicleModelChemical.EventId = uint32(modelDataId)
		vehicleModelChemical.HazardousChemical = s
		_, insertError := vehicleModelChemical.Insert()
		if insertError != nil {
			common.Logger.Errorf("insert vehicleModelChemical error %v", insertError)
			return insertError
		}
	}

	return nil
}
